package com.ruoyi.base.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.base.mapper.BaseCatalogMapper;
import com.ruoyi.base.domain.BaseCatalog;
import com.ruoyi.base.service.IBaseCatalogService;

/**
 * 数据目录Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-02-12
 */
@Service
public class BaseCatalogServiceImpl implements IBaseCatalogService 
{
    private static final Logger log = LoggerFactory.getLogger(BaseCatalogServiceImpl.class);

    @Autowired
    private BaseCatalogMapper baseCatalogMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询数据目录
     * 
     * @param id 数据目录主键
     * @return 数据目录
     */
    @Override
    public BaseCatalog selectBaseCatalogById(Long id)
    {
        return baseCatalogMapper.selectBaseCatalogById(id);
    }

    /**
     * 查询数据目录列表
     * 
     * @param baseCatalog 数据目录
     * @return 数据目录
     */
    @Override
    public List<BaseCatalog> selectBaseCatalogList(BaseCatalog baseCatalog)
    {
        return baseCatalogMapper.selectBaseCatalogList(baseCatalog);
    }

    /**
     * 新增数据目录
     * 
     * @param baseCatalog 数据目录
     * @return 结果
     */
    @Override
    public int insertBaseCatalog(BaseCatalog baseCatalog)
    {
        BaseCatalog old = baseCatalogMapper.selectBaseCatalogByCode(baseCatalog.getCode());
        if(old != null){
            throw new ServiceException("数据目录'"+old.getCode()+"'已存在");
        }
        BaseCatalog info = baseCatalogMapper.selectBaseCatalogById(baseCatalog.getPid());
        if(info != null) {
            baseCatalog.setAncestors(info.getAncestors() + "," + baseCatalog.getParentId());
        }else{
            baseCatalog.setAncestors("0");
        }

        baseCatalog.setCreateTime(DateUtils.getNowDate());
        return baseCatalogMapper.insertBaseCatalog(baseCatalog);
    }

    /**
     * 修改数据目录
     * 
     * @param baseCatalog 数据目录
     * @return 结果
     */
    @Override
    public int updateBaseCatalog(BaseCatalog baseCatalog)
    {
        BaseCatalog old = baseCatalogMapper.selectBaseCatalogByCode(baseCatalog.getCode());
        if(old != null && !old.getId().equals(baseCatalog.getId())){
            throw new ServiceException("数据目录'"+old.getCode()+"'已存在");
        }

        BaseCatalog oldCate = baseCatalogMapper.selectBaseCatalogById(baseCatalog.getId());
        BaseCatalog newParent = baseCatalogMapper.selectBaseCatalogById(baseCatalog.getPid());
        if (StringUtils.isNotNull(newParent) && StringUtils.isNotNull(oldCate))
        {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = oldCate.getAncestors();
            baseCatalog.setAncestors(newAncestors);
            updateCataChildren(baseCatalog.getId(), newAncestors, oldAncestors);
        }

        baseCatalog.setUpdateTime(DateUtils.getNowDate());
        return baseCatalogMapper.updateBaseCatalog(baseCatalog);
    }

    /**
     * 修改子元素关系
     *
     * @param cateId 被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCataChildren(Long cateId, String newAncestors, String oldAncestors)
    {
        List<BaseCatalog> children = baseCatalogMapper.selectChildrenById(cateId);
        for (BaseCatalog child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            baseCatalogMapper.updateChildren(children);
        }
    }

    /**
     * 批量删除数据目录
     * 
     * @param ids 需要删除的数据目录主键
     * @return 结果
     */
    @Override
    public int deleteBaseCatalogByIds(Long[] ids)
    {
        return baseCatalogMapper.deleteBaseCatalogByIds(ids);
    }

    /**
     * 删除数据目录信息
     * 
     * @param id 数据目录主键
     * @return 结果
     */
    @Override
    public int deleteBaseCatalogById(Long id)
    {
        return baseCatalogMapper.deleteBaseCatalogById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<BaseCatalog> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, Long> cataMap = baseCatalogMapper.selectBaseCatalogList(new BaseCatalog()).stream().collect(Collectors.toMap(BaseCatalog::getName, BaseCatalog::getId));
        for (BaseCatalog row : dataList)
        {
            try
            {
                if(StringUtils.isNotEmpty(row.getPname())){
                    row.setPid(cataMap.get(row.getPname()));
                }else{
                    row.setPid(0L);
                }
                BeanValidators.validateWithException(validator, row);

                // 验证是否存在旧数据
                BaseCatalog old = baseCatalogMapper.selectBaseCatalogByCode(row.getCode());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertBaseCatalog(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据目录 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setUpdateBy(operName);
                    row.setId(old.getId());
                    updateBaseCatalog(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据目录 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、数据目录 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、数据目录 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
